//
//  CYGRightViewController.m
//  CYGHuntForCity
//
//  Created by cygarm on 16/5/4.
//  Copyright © 2016年 cygarm. All rights reserved.
//

#import "CYGRightViewController.h"
#import "UIView+CYGEx.h"
#import "UIViewController+CYGNaviBar.h"

@interface CYGRightViewController () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIButton *coverBtn;
@property (nonatomic, assign) CGPoint preVelocity;

@end

@implementation CYGRightViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
	[self setUpBar];
	
	UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(movePanel:)];
	[pan setMinimumNumberOfTouches:1];
	[pan setMaximumNumberOfTouches:1];
	[pan setDelegate:self];
	
	[self.navigationController.view addGestureRecognizer:pan];
}

- (void) setUpBar {
	[self cyg_initNavigationBar:self.navigationController.navigationBar];
	
	// 这里的图片由于像素不符,变形了
	// 1.自定义frame的button   2.imageInsets
	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"artcleList_btn_info"] style:UIBarButtonItemStylePlain target:self action:@selector(MenuBtnClick:)];
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(SearchBtnClick:)];
	self.navigationItem.leftBarButtonItem.imageInsets = UIEdgeInsetsMake(4, 4, 4, 4);
	self.navigationItem.rightBarButtonItem.imageInsets = UIEdgeInsetsMake(4, 4, 4, 4);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - IBAction
- (IBAction)MenuBtnClick:(id)sender {
	[self moveToRight];
}

- (IBAction)SearchBtnClick:(id)sender {
	
}

// 当gesture在scrollview或者tableview上时，使能gesture检测
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (void)movePanel:(UIPanGestureRecognizer *)gesture {	
	UIView *gestureView = [gesture view];
	[[gestureView layer] removeAllAnimations];
	
	static BOOL _panNeedCancel = false;
	static CGFloat _preTranslatedPointX = 0;
	
	CGFloat currentPointX = [gesture locationInView:gestureView].x;
	CGFloat translatedPointX = [gesture translationInView:[[[UIApplication sharedApplication] delegate] window]].x;
	CGPoint velocity = [gesture velocityInView:gestureView];
	
	if (gesture.state == UIGestureRecognizerStateBegan) {
		_preTranslatedPointX = 0;
		_panNeedCancel = false;
		if (currentPointX-gestureView.frame.origin.x > gestureView.bounds.size.width*1/5 ||
			(velocity.x < 0 && gesture.view.left <= 0)) {
			_panNeedCancel = true;
//			DLog(@"_panNeedCancel");
		}
	}
    
    if (velocity.x < 0 && gesture.view.left <= 0) {
        gesture.view.left = 0;
        _panNeedCancel = true;
    }
	
	if (_panNeedCancel) {
		return;
	}
	
	if (gesture.state == UIGestureRecognizerStateChanged) {
		CGFloat dx = translatedPointX-_preTranslatedPointX;;
		gestureView.left += dx;
		CGFloat scale = 1-(gestureView.left*(1-CYGLeftMenuShowNaviSegueZoomScale)/(gestureView.bounds.size.width*3/4));
		[gestureView cyg_viewScale:scale];
		
#if 0
		if (velocity.x > 0) {
			DLog(@">>>");
		} else {
			DLog(@"<<<");
		}
		DLog(@"translatedPointX=%f, preTranslatedPointX=%f, scale=%f", translatedPointX, _preTranslatedPointX, scale);
#endif
		_preTranslatedPointX = translatedPointX;
	}
	
	if (gesture.state == UIGestureRecognizerStateEnded ||
		gesture.state == UIGestureRecognizerStateCancelled ||
		gesture.state == UIGestureRecognizerStateFailed) {
		DLog(@"gesture.state=%@", gesture.state==UIGestureRecognizerStateEnded?@"ended":(gesture.state==UIGestureRecognizerStateCancelled?@"canceled":@"failed"));
		
		if (gestureView.frame.origin.x > gestureView.bounds.size.width/2) {
			[self moveToRight];
		} else {
			[self moveToFull];
		}
	}
}

- (void)scaleToRight {
	CGFloat movex;
	
	movex = [UIScreen mainScreen].bounds.size.width*CYGLeftMenuShowNaviSegueZoomScale-self.navigationController.view.left;
	CGAffineTransform transform = CGAffineTransformMakeScale(CYGLeftMenuShowNaviSegueZoomScale, CYGLeftMenuShowNaviSegueZoomScale);
	self.navigationController.view.transform = CGAffineTransformTranslate(transform, movex, 0);
}

- (void)moveToRight {
	CGFloat movex, duration;
	
	movex = [UIScreen mainScreen].bounds.size.width*CYGLeftMenuShowNaviSegueZoomScale-self.navigationController.view.left;
	duration = CYGLeftMenuShowNaviSegueAnimateDuration*movex/([UIScreen mainScreen].bounds.size.width*CYGLeftMenuShowNaviSegueZoomScale);
//	DLog(@"showPanel: movex=%f, duration=%f", movex, duration);
	[UIView animateWithDuration:duration animations:^{
		CGAffineTransform transform = CGAffineTransformMakeScale(CYGLeftMenuShowNaviSegueZoomScale, CYGLeftMenuShowNaviSegueZoomScale);
		self.navigationController.view.transform = CGAffineTransformTranslate(transform, movex, 0);
	} completion:^(BOOL finished) {
		_coverBtn = [UIButton buttonWithType:UIButtonTypeSystem];
		_coverBtn.backgroundColor = [UIColor clearColor];
		[self.navigationController.view addSubview:_coverBtn];
		_coverBtn.frame = self.navigationController.view.bounds;
		[_coverBtn addTarget:self action:@selector(moveToFull) forControlEvents:UIControlEventTouchUpInside];

	}];
}

- (void)moveToFull {
	CGFloat duration;
	
	duration = CYGLeftMenuShowNaviSegueAnimateDuration*self.navigationController.view.left/([UIScreen mainScreen].bounds.size.width*CYGLeftMenuShowNaviSegueZoomScale);
//	DLog(@"reset: left=%f, duration=%f", self.navigationController.view.left, duration);
	[UIView animateWithDuration:duration animations:^{
		self.navigationController.view.transform = CGAffineTransformIdentity;
		self.navigationController.view.left = 0;
	} completion:^(BOOL finished) {
		[_coverBtn removeFromSuperview];
	}];
}

@end
